<?php

namespace backend\modules\business\controllers;

use arogachev\excel\import\basic\Importer;
use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPigImport;
use backend\modules\business\models\Test;
use common\components\PHPZip;
use common\components\Upload;
use common\components\ZipArchive;
use common\models\business\BusinessBackpig;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessPerson;
use common\models\business\BusinessPigFile;
use common\models\business\BusinessVariety;
use dosamigos\qrcode\QrCode;
use kartik\helpers\Html;
use Yii;
use common\models\business\BusinessPig;
use backend\modules\business\models\BusinessPigSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * PigController implements the CRUD actions for BusinessPig model.
 */
class PigController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $params = Yii::$app->request->queryParams;

        $ids = Yii::$app->request->get('ids');
        if(!empty($ids)){
            $idarr = explode(',',$ids);
        }else{
            $idarr =[];
        }
        unset($ids);


        $searchModel = new BusinessPigSearch();
        $dataProvider = $searchModel->search($params);
        $immodel = new BusinessPigImport();

        $varietys = (new Query())->select('id,title')
            ->from(BusinessVariety::tableName())
            ->all();
        $varietys = $varietys?ArrayHelper::map($varietys,'id','title'):[];



        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'immodel' => $immodel,
            'idarr' => \GuzzleHttp\json_encode($idarr),
            'varietys' => $varietys
        ]);
    }


    /**
     * Displays a single BusinessPig model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessPig model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessPig();

        if ($model->load(Yii::$app->request->post())) {
            if($model->livery){
                $livery = BusinessFarmers::findOne(['id'=> $model->livery]);
                $model->setAttribute('liveryname',$livery->name);
            }else{
                $model->livery = 0;
            }
            if($model->headpersonid){
                $person = BusinessPerson::findOne(['id'=> $model->headpersonid]);
                $model->setAttribute('headperson',$person->name);
            }else{
                $model->headpersonid = 0;
            }
            if(false !== $photo = Upload::upload($model,'photo')){
                $model->setAttribute('photo',$photo);
            }
            if(false !== $sphoto = Upload::upload($model,'screen_photo')){
                $model->setAttribute('screen_photo',$sphoto);
            }

            if(false !== $video = Upload::upload($model,'video','video')){
                $model->setAttribute('video',$video);
            }

            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
               return $this->dialog($this->checkError($model));
            }
        } else {

            //仔猪出栏不能直接操作
            unset(BusinessPig::$statues[BusinessPig::STATUS_WAITOUT]);
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing BusinessPig model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())){

            $model->setScenario('update');
            if(false !== $photo = Upload::upload($model,'photo')){
                $model->setAttribute('photo',$photo);
            }
            if(false !== $sphoto = Upload::upload($model,'screen_photo')){
                $model->setAttribute('screen_photo',$sphoto);
            }


            if(false !== $video = Upload::upload($model, $name = 'video',$type='video')){
                //删除旧视频
//                $videofile = Upload::checkGetPath($model->oldAttributes['video']);
//                if(is_file($videofile) && file_exists($videofile)){
//                    unlink($videofile);
//                }
                $model->setAttribute('video',$video);
            }else{
                unset($model->video);
            }


            if($model->livery){
                $livery = BusinessFarmers::findOne(['id'=>$model->livery]);
                $model->setAttribute('liveryname',$livery->name);
            }
            if($model->headpersonid){
                $person = BusinessPerson::findOne(['id'=>$model->headpersonid]);
                if($person){
                    $model->setAttribute('headperson',$person->name);
                }
            }

            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->dialog($this->checkError($model));
            }
        } else {
            $model->setScenario('update');
            $model->beforevaccinetime = date('Y-m-d',$model->beforevaccinetime);
            $model->aftervaccinetime =date('Y-m-d',$model->aftervaccinetime);
            $model->intime = date('Y-m-d',$model->intime);
            $model->planout = date('Y-m-d',$model->planout);
            unset(BusinessPig::$statues[BusinessPig::STATUS_WAITOUT]);
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing BusinessPig model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }


    /**
     * 上传仔猪
     */
    public function actionImport()
    {
        $model = new BusinessPigImport();
        $excel = Upload::upload($model,'excel','2bin/excel');
        if($aa = (new BusinessPigImport())->import($excel)) {
            if($aa !== true){
                return $this->dialog($aa,'warning','/business/pig/index');
            }
           $this->redirect('index');
        }
        return $this->dialog('上传错误','warning','/business/pig/index');
    }


    /**
     * @return $this|string
     * 批量下载仔猪二维码
     */
    public function actionDownloadQr()
    {
        $ids = Yii::$app->request->get('ids');
        if(empty($ids)){
            return $this->dialog('请选择对应的仔猪');
        }
        $idarr = explode(',',$ids);
        $pigs = BusinessPig::find()->select('no')->where(['in', 'id', $idarr])->asArray()->all();

        //临时目录
        $basetmpdir = Yii::getAlias('@uploadpath').'/tmpfile/';
        $tmpdir = $basetmpdir.time().'/';
        FileHelper::createDirectory($tmpdir);

        //生成二维码
        foreach ($pigs as $key => $row){
            QrCode::jpg(Yii::getAlias('@fdomain').'/shop/site/from?pigid='.$row['no'],$tmpdir.$row['no'].'.png');
        }

        //压缩
        $zipfile = Yii::getAlias('@uploadpath').'/tmpfile/'.time().'.zip';
        (new PHPZip)->Zip($tmpdir,$zipfile);

        //删除临时文件
        FileHelper::removeDirectory($tmpdir);
        return Yii::$app->response->sendFile($zipfile);
    }




    //批量生成仔猪编号
    public function actionCreateno()
    {

        if(Yii::$app->request->isPost){
            $postdata = Yii::$app->request->post();
            $basenum = $postdata['basenum'];
            $endnum = $postdata['endnum'];

            if($basenum<0 || $endnum<0){
                return $this->dialog('编号不能为负数');
            }

            $numlen = strlen($endnum);

            for ($i = $basenum; $i <= $endnum; $i++){

                $data = [
                    'no' => $postdata['formatno'].sprintf("%0{$numlen}d",$i),
                    'status' => BusinessPig::STATUS_BRFOREIN,
                    'unino' => '',
                ];
                $ise = Yii::$app->db->createCommand('select 1 from '.BusinessPig::tableName().' where no=:no')->bindValues([':no'=>$data['no']])->queryOne();
                if(!empty($ise)){
                    return $this->dialog('编号'.$data['no'].'已经存在');
                }
                $res = Yii::$app->db->createCommand()->insert(BusinessPig::tableName(),$data)->execute();
                $id = Yii::$app->db->getLastInsertID();
                $ids[] = $id;
            }

//            return $res?json_encode(['msg'=>'生成成功','status'=>0]):json_encode(['msg'=>'生成失败','status'=>1]);
            return $res?$this->dialog('生成成功','success',Url::to(['index','BusinessPigSearch[no]'=>$postdata['formatno'],'_toga654c069'=>'all','ids'=>implode(',',$ids)])):$this->dialog('生成失败');
        }

        $this->layout = false;
        return $this->render('createno');
    }


    /**
     * @return string
     * 批量删除仔猪
     */
    public function actionDeletepigs()
    {
        $postdata = Yii::$app->request->post();
        if(empty($postdata['ids'])){
            return json_encode(['msg'=>'请选择要删除的仔猪','status'=>1]);
        }
        $ids = implode(',',$postdata['ids']);
        $res = Yii::$app->db->createCommand('delete from '.BusinessPig::tableName().' where id in ('.$ids.')')->execute();

        return $res?json_encode(['msg'=>'删除成功','status'=>0]):json_encode(['msg'=>'删除失败','status'=>1]);

    }


    //批量设置仔猪信息
    public function actionSettime()
    {

        if(Yii::$app->request->isPost) {
            $postdata = Yii::$app->request->post();
//            $beforevaccinetime = $postdata['beforevaccinetime'];
            $intime = $postdata['intime'];
            $tooutnum = intval($postdata['tooutnum']);

            if (!empty($intime)) {
                if(!empty($tooutnum)){
                    //计算预出栏时间
                    $planout = strtotime('+' . $tooutnum . ' days', strtotime($intime));
                }
            }

            $idarr = explode(',',Yii::$app->request->post('ids'));
            $res = false;

            $liveryname = '';
            if(!empty($postdata['livery'])){
                $liveryname = BusinessFarmers::findOne($postdata['livery'])->name;
            }

            $personname = '';
            if(!empty($postdata['headpersonid'])){
                $personname = BusinessPerson::findOne($postdata['headpersonid'])->name;
            }

            foreach ($idarr as $key => $row){

                $data = [
                    'isindex' => $postdata['isindex'],
                    'canlivery' => $postdata['canlivery'],
                ];
                if(!empty($postdata['batch'])){
                    $data['batch'] = $postdata['batch'];
                }

                if(!empty($postdata['status'])){
                    $data['status'] = $postdata['status'];
                }

                if(!empty($tooutnum)){
                    $data['planout'] = $planout;
                }

                if(!empty($postdata['price'])){
                    $data['price'] = $postdata['price'];
                }

                if(!empty($postdata['fileid'])){
                    $data['fileid'] = $postdata['fileid'];
                }

                if(strtotime($intime) != 0){
                    $data['intime'] = strtotime($intime);
                }

//                if(strtotime($beforevaccinetime) != 0){
//                    $data['beforevaccinetime'] = strtotime($beforevaccinetime);
//                }
                if(!empty($postdata['varietyid'])){
                    $data['varietyid'] = $postdata['varietyid'];
                }

                if(!empty($postdata['livery'])){
                    $data['livery'] = $postdata['livery'];
                    $data['liveryname'] = $liveryname;
                }

                if(!empty($postdata['headpersonid'])){
                    $data['headpersonid'] = $postdata['headpersonid'];
                    $data['headperson'] = $personname;
                }

                $res = Yii::$app->db->createCommand()->update(BusinessPig::tableName(),$data,'id=:id',[':id'=>$row])->execute();
            }
            return $res?$this->dialog('设置成功','success',Url::to('index')):$this->dialog('生成失败');
        }
    }


    /**
     * @return string
     *  批量设置仔猪成本和价格
     */
    public function actionSetPigcost()
    {

        if(Yii::$app->request->isPost) {
            $postdata = Yii::$app->request->post();
            if(empty($postdata['ids'])){
                return json_encode(['msg'=>'请选择要设置的仔猪','status'=>1]);
            }
            $idarr = explode(',',Yii::$app->request->post('ids'));
            $res = false;
            $data = [
                'cost' => $postdata['cost'],
                'price' => $postdata['price'],
            ];

            $res = Yii::$app->db->createCommand()->update(BusinessPig::tableName(),$data,['id'=>$idarr])->execute();

            return $res?$this->dialog('设置成功','success',Url::to('index')):$this->dialog('设置失败');
        }
        $ids = Yii::$app->request->get('ids');
        if(!empty($ids)){
            $ids = implode(',',$ids);
        }
//        var_dump($ids);exit;
        $this->layout = false;
        return $this->render('_setpigcost',[
            'ids' => $ids
        ]);

    }


    /**
     * @return string
     * 仔猪异常
     */
    public function actionException($pigid)
    {

        return $this->renderPartial('exception');
    }




    /**
     * @param $no
     * 二维码
     */
    public function actionQrcode($no)
    {
        return QrCode::png(Yii::getAlias('@fdomain').'/shop/site/from?pigid='.$no);
    }


    /**
     *
     * 取消认养
     */
    public function actionQxLing($id)
    {
        $id = Yii::$app->request->get('id');
        if(empty($id)){
            return $this->dialog("请选择要取消认养人的仔猪");
        }
        $res = Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['lingperson'=>0],['id'=>intval($id)])->execute();

        return $res?$this->dialog("操作成功"):$this->dialog("操作成功");
    }






    /**
     * Finds the BusinessPig model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return BusinessPig the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessPig::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
